<script setup lang="tsx">
import markdownItLinkAttributes from 'markdown-it-link-attributes'
import { config, MdPreview } from 'md-editor-v3'
import { ref, unref, useAttrs, watch } from 'vue'
import { mdHeadingId } from '../../config'
import 'md-editor-v3/lib/style.css'

const props = defineProps<{
  modelValue: string
  editorId: string
}>()

const emits = defineEmits<{
  (e: 'update:modelValue', text: string): void
}>()

config({
  markdownItConfig(mdit) {
    // 新标签页打开链接
    mdit.use(markdownItLinkAttributes, {
      pattern: /^http/i,
      attrs: {
        target: '_blank',
        rel: 'noopener',
      },
    })
  },
})

const text = ref('')

// 监听
watch(text, (val: string) => {
  emits('update:modelValue', val)
})
watch(
  () => props.modelValue,
  (val: string) => {
    if (val === unref(text))
      return
    text.value = val
  },
  {
    immediate: true,
  },
)
const attrs = useAttrs()
</script>

<template>
  <MdPreview
    v-model="text"
    :editor-id="editorId"
    :md-heading-id="mdHeadingId"
    v-bind="attrs"
  />
</template>

<style lang="less" scoped></style>
